package whf.framework.report;

import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

import whf.framework.log.Log;
import whf.framework.log.LogFactory;
import whf.framework.util.Utils;

/**
 * @author King
 * @create Jan 17, 2008 1:59:29 PM
 */
public class ReportFactory {
	private static Log log = LogFactory.getLog(ReportFactory.class);
	
	private Map<String, Class<? extends ReportExporter>> reportExporterTypes = Utils.newHashMap();
	private static ReportFactory instance;

	private ReportFactory() {
		InputStream is = null;
		try{
			is = ReportFactory.class.getResourceAsStream("report.conf");
			if(is == null) {
				throw new RuntimeException("report config file: 'report.conf' not found!");
			}
			Properties props = new Properties();
			props.load(is);
			for(java.util.Iterator<Object> keys = props.keySet().iterator(); keys.hasNext();) {
				try{
					String reportType = (String)keys.next();
					String className = props.getProperty(reportType);
					Class<? extends ReportExporter> cls = Utils.getClassByClassName(className);
					reportExporterTypes.put(reportType, cls);
					log.debug(reportType + "\t" + className);
				}catch(Exception e){
					log.error(this, e);
				}
			}
		} catch(RuntimeException e){
			throw e;
		} catch(Exception e){
			throw new RuntimeException("Initializing report factory failure!");
		} finally {
			if(is != null) {
				try{
					is.close();
				} catch(Exception e){
					log.warn(this, e);
				}
			}
		} 
	}
	
	public static ReportFactory getInstance() {
		if(instance == null) {
			instance = new ReportFactory();
		}
		return instance;
	}
	
	/**
	 * @param reportType
	 * @return
	 */
	public ReportExporter getReportExporter(String reportType) throws ReportExporterNotFoundException {
		Class<? extends ReportExporter> cls = this.reportExporterTypes.get(reportType);
		try{
			return cls.newInstance();
		} catch(Exception e){
			log.error(this, e);
			throw new ReportExporterNotFoundException(e);
		}
	}
	
	public static void main(String[] args) throws Exception {
		ReportFactory.getInstance();
	}
}
